import time
from typing import List

import pandas as pd
import akshare as ak
import model.stock_index as stock_index


#  定义获取指数列表函数
def get_index_list() -> List[stock_index.StockIndex]:
    index_list = []
    index_list.append(stock_index.StockIndex('H11136', '中国互联网'))
    index_list.append(stock_index.StockIndex('H30533', '中国互联网50'))
    index_list.append(stock_index.StockIndex('930604', '中国互联网30'))
    return index_list

class CommInfo:
    def __init__(self, cnt, percent):
        self.cnt = cnt
        self.percent = percent
def get_comm_index(a: List[str], b: List[str]) -> CommInfo:
    total = len(a) + len(b)
    commCnt, percent = 0, 0
    for e in a:
        for e2 in b:
           if e == e2:
                commCnt += 1
                break
    percent = round(commCnt * 2 * 100 / total)
    return CommInfo(commCnt, percent)



# 第一步 获取指数成分
idxMap = {}
idxList = get_index_list()
idxNames = []
for e in idxList:
    df = ak.index_stock_cons_weight_csindex(e.code)
    # df = ak.index_stock_cons_sina(e.code)
    print(f'{e.name} {e.code}获取数据成功')
    idxMap[e.code] = df['成分券代码'].tolist()
    idxNames.append(f'{e.name}-{df.shape[0]}')

data = {}
for e in idxList:
    percents = []
    for e2 in idxList:
        total = len(idxMap[e.code]) + len(idxMap[e2.code])
        comm = get_comm_index(idxMap[e.code], idxMap[e2.code])
        percents.append(f'{comm.cnt}-{comm.percent}%')
    data[f'{e.name}-{len(idxMap[e.code])}'] = percents

df = pd.DataFrame(index=idxNames, data=data)
print(df)
date = time.strftime("%Y%m%d", time.localtime())
df.to_excel(f'指数相似度-{date}.xlsx')

